<template>
  <div class="borrow-management-container">
    <NavTop />

    <div class="content-wrapper">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-content">
          <h1 class="page-title">
            <i class="el-icon-reading"></i>
            借阅管理中心
          </h1>
          <p class="page-subtitle">管理您的图书借阅申请、借阅记录和历史信息</p>
        </div>

        <!-- 快捷统计 -->
      </div>

      <!-- 标签页内容 -->
      <div class="tabs-container">
        <el-tabs
            v-model="activeTab"
            type="border-card"
            @tab-click="handleTabClick"
            class="management-tabs"
        >
          <el-tab-pane name="apply" lazy>
            <template #label>
              <span class="tab-label">
                <i class="el-icon-edit-outline"></i>
                借阅申请
                <el-badge
                    v-if="borrowStats.pending > 0"
                    :value="borrowStats.pending"
                    class="tab-badge"
                />
              </span>
            </template>
            <BorrowApply
                @submit-success="handleSubmitSuccess"
                :loading="loading.applying"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <el-backtop :visibility-height="100" />
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { debounce } from 'lodash-es'
import { useBorrowStore } from '@/store/borrow'
import NavTop from "@/components/NavTop.vue"
import BorrowApply from './BorrowApply.vue'
import MyBorrows from "@/views/Borrows/MyBorrows.vue";

// import FabButton from '@/components/FabButton.vue'

export default {
  name: 'BorrowManagement',
  components: {
    NavTop,
    BorrowApply,
    MyBorrows,
    // HistoryTab,
    // FabButton
  },
  setup() {
    const borrowStore = useBorrowStore()
    const activeTab = ref('apply')

    // 加载状态
    const loading = reactive({
      borrowList: false,
      historyList: false,
      applying: false,
      returning: false
    })

    // 从store获取数据
    const borrowList = computed(() => borrowStore.borrowList)
    const historyList = computed(() => borrowStore.historyList)

    // 计算统计信息
    const borrowStats = computed(() => {
      const stats = {
        total: borrowList.value.length,
        active: 0,
        pending: 0,
        overdue: 0,
        returned: 0
      }

      borrowList.value.forEach(item => {
        switch (item.status) {
          case 'PENDING':
            stats.pending++
            stats.active++
            break
          case 'APPROVED':
            if (!item.actualReturnDate) {
              stats.active++
              if (new Date(item.expectedReturnDate) < new Date()) {
                stats.overdue++
              }
            }
            break
          case 'RETURNED':
            stats.returned++
            break
        }
      })

      return stats
    })

    // 防抖刷新
    const refreshBorrows = debounce(async (showMessage = false) => {
      loading.borrowList = true
      try {
        await borrowStore.fetchBorrowList()
        if (showMessage) {
          window.$message?.success('借阅列表已更新')
        }
      } catch (error) {
        console.error('获取借阅列表失败:', error)
        window.$message?.error('获取借阅列表失败，请稍后重试')
      } finally {
        loading.borrowList = false
      }
    }, 500)

    const refreshHistory = debounce(async (showMessage = false) => {
      loading.historyList = true
      try {
        await borrowStore.fetchBorrowHistory()
        if (showMessage) {
          window.$message?.success('历史记录已更新')
        }
      } catch (error) {
        console.error('获取借阅历史失败:', error)
        window.$message?.error('获取借阅历史失败，请稍后重试')
      } finally {
        loading.historyList = false
      }
    }, 500)

    // 处理标签页切换
    const handleTabClick = (tab) => {
      if (tab.name === 'myBorrows' && borrowList.value.length === 0) {
        refreshBorrows()
      } else if (tab.name === 'history' && historyList.value.length === 0) {
        refreshHistory()
      }
    }

    // 处理归还书籍
    const handleReturnBook = async (borrowId) => {
      loading.returning = true
      try {
        await borrowStore.returnBook(borrowId)
        window.$message?.success('归还申请已提交，请等待审核')
        refreshBorrows()
      } catch (error) {
        console.error('归还申请提交失败:', error)
        window.$message?.error('归还申请提交失败，请稍后重试')
      } finally {
        loading.returning = false
      }
    }

    // 其他方法
    const handleSubmitSuccess = () => {
      window.$message?.success('借阅申请提交成功！')
      activeTab.value = 'myBorrows'
      refreshBorrows()
    }

    const handleCancelSuccess = () => {
      refreshBorrows()
    }

    const goToApply = () => {
      activeTab.value = 'apply'
    }

    const exportHistory = () => {
      borrowStore.exportHistory()
    }

    // 初始化数据
    onMounted(() => {
      refreshBorrows()
      refreshHistory()
    })

    return {
      activeTab,
      loading,
      borrowStats,
      borrowList,
      historyList,
      refreshBorrows,
      refreshHistory,
      handleTabClick,
      handleReturnBook,
      handleSubmitSuccess,
      handleCancelSuccess,
      goToApply,
      exportHistory
    }
  }
}
</script>

<style lang="scss" scoped>
.borrow-management-container {
  min-height: 100vh;
  background: var(--bg-gradient);
  transition: all 0.3s ease;

  // 使用CSS变量实现主题切换
  --bg-gradient: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  --card-bg: white;
  --card-border: rgba(255, 255, 255, 0.8);
  --text-primary: #1a202c;
  --text-secondary: #718096;
  --border-color: #e2e8f0;

  &.dark-mode {
    --bg-gradient: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
    --card-bg: #2d3748;
    --card-border: #4a5568;
    --text-primary: #f7fafc;
    --text-secondary: #a0aec0;
    --border-color: #4a5568;
  }
}

.content-wrapper {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  margin-bottom: 24px;
  padding: 24px;
  background: var(--card-bg);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid var(--card-border);
}

.header-content {
  flex: 1;
  min-width: 250px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 12px;

  i {
    color: #3182ce;
    font-size: 32px;
  }
}

.page-subtitle {
  margin: 0;
  color: var(--text-secondary);
  font-size: 16px;
  line-height: 1.5;
}

/* 快捷统计样式 */
.quick-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  min-width: fit-content;
}

/* 标签页容器样式 */
.tabs-container {
  background: var(--card-bg);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.management-tabs {
  border: none;
  box-shadow: none;

  :deep(.el-tabs__header) {
    background: var(--card-bg);
    border-bottom: 1px solid var(--border-color);
    margin: 0;
  }

  :deep(.el-tabs__item) {
    color: var(--text-secondary);
    font-weight: 500;
    padding: 0 24px;
    height: 48px;
    line-height: 48px;
    transition: all 0.3s ease;

    &:hover {
      color: #3182ce;
    }

    &.is-active {
      background: var(--card-bg);
      color: #3182ce;
      border-bottom: 2px solid #3182ce;
    }
  }
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-wrapper {
    padding: 12px;
  }

  .page-header {
    padding: 20px;
  }

  .page-title {
    font-size: 24px;

    i {
      font-size: 28px;
    }
  }

  .quick-stats {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .management-tabs {
    :deep(.el-tabs__item) {
      padding: 0 12px;
      font-size: 14px;
    }
  }
}
</style>